package com.wz.jaav.classreader.classFile.attribute;

import com.wz.jaav.BootStrap;
import com.wz.jaav.classreader.ClassReader;
import com.wz.jaav.classreader.classFile.ConstantPool;
import com.wz.jaav.classreader.classFile.constant.ConstantInfo;
import com.wz.jaav.classreader.classFile.constant.ConstantUtf8;
import com.wz.jaav.util.CommonUtils;

public class Attribute {
    private short nameIndex;
    private int length;
    private AttributeInfo info;

    public Attribute() {}

    public void build(ClassReader cr) {
        byte[] ni = cr.doRead(2);
        short nameIndex = CommonUtils.byteToShort(ni);
        this.nameIndex = nameIndex;
        byte[] len = cr.doRead(4);
        int length = CommonUtils.bytes2Int(len);
        this.length = length;
        byte[] attributeContent = cr.doRead(length);
        System.out.println("      attribute code:" + CommonUtils.bytesToHex(attributeContent));
        if (isCode(nameIndex)) {
            info = new AttributeInfoCode();
            ((AttributeInfoCode)info).build(attributeContent);
        } else {
            info = new AttributeInfoOther(BootStrap.cf.getConstantPool().getById(nameIndex).toString());
            ConstantInfo constantInfo = BootStrap.cf.getConstantPool().getById(nameIndex);
            System.out.println("此信息是" + constantInfo.toString() + "除code外其他的暂时不做解析");
        }
    }

    public boolean isCode(short nameIndex) {
        ConstantInfo constantInfo = BootStrap.cf.getConstantPool().getById(nameIndex);
        if (constantInfo instanceof ConstantUtf8) {
            String str = ((ConstantUtf8) constantInfo).getString().toLowerCase();
            return str.equals("code");
        } else {
            //FIXME
            System.out.println("未识别的类型!");
            return false;
        }
    }

    public boolean isLocalVariableTable(short nameIndex) {
        ConstantInfo constantInfo = BootStrap.cf.getConstantPool().getById(nameIndex);
        if (constantInfo instanceof ConstantUtf8) {
            String str = ((ConstantUtf8) constantInfo).getString().toLowerCase();
            return str.equals("localvariabletable");
        } else {
            //FIXME
            System.out.println("未识别的类型!");
            return false;
        }
    }

    public AttributeInfo getInfo() {
        return info;
    }

    @Override
    public String toString() {
        return "Attribute{" +
                "nameIndex=" + nameIndex +
                ", length=" + length +
                '}';
    }

    public void printInfos(String placeholder) {
        System.out.println(placeholder + toString());
        info.printInfos(placeholder);
    }
}